/**************************************************************************
** CuteRSS is a simple RSS/Atom client for managing RSS/Atom Feeds
**
** Copyright (C) 2010 Prakash Nadar <prakash.nadar@gmail.com>
**
** This program is free software: you can redistribute it and/or modify
**     it under the terms of the GNU General Public License as published by
**     the Free Software Foundation, either version 3 of the License, or
**     (at your option) any later version.
**
**     This program is distributed in the hope that it will be useful,
**     but WITHOUT ANY WARRANTY; without even the implied warranty of
**     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**     GNU General Public License for more details.
**
**     You should have received a copy of the GNU General Public License
**     along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QString>
#include <QDomDocument>

#include "feedfetcher.h"
#include "rssdata.h"

#include <QDebug>

FeedFetcher::FeedFetcher(QObject *parent) :
    QObject(parent)
{
    netReply = 0;
    mNetManager = new QNetworkAccessManager(this);
}


bool FeedFetcher::readFeeds()
{
    qDebug() << "Fetching: " << mUrl;
    netReply = mNetManager->get( QNetworkRequest( QUrl( mUrl)));

    connect(netReply,SIGNAL(finished()),this,SLOT(finished()));
    connect(netReply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(error(QNetworkReply::NetworkError)));

    return true;
}

void FeedFetcher::finished()
{
    QString xmlData = netReply->readAll();

    xmlFeedParse(xmlData);
    netReply->deleteLater();
    netReply = 0;
}

void FeedFetcher::error ( QNetworkReply::NetworkError code )
{
    qDebug() << "Error";
}

bool FeedFetcher::xmlFeedParse(QString& xml)
{
    RssFetchData* result = new RssFetchData();
    QDomDocument rssXmlDoc;
    rssXmlDoc.setContent(xml); //TODO: Error check here.
    xml = "";

    QDomElement docElem = rssXmlDoc.documentElement();
    QDomNodeList accountList = docElem.elementsByTagName("channel").at(0).toElement().elementsByTagName("item");

    for(int i = 0; i < accountList.count(); i++)
    {
        RssItemData* item = new RssItemData();
        item->mRead = false;
        QDomNodeList children = accountList.at(i).childNodes();
        for(int k = 0; k < children.count(); k++) {
            QDomNode node = children.at(k);
            QString nodeName = node.nodeName();

            if(nodeName == "link")  {
                item->mLink = node.toElement().text();
            }
            else if(nodeName == "title") {
                item->mTitle = node.toElement().text();
            }
            else if(nodeName == "pubDate") {
                item->mPubDate = node.toElement().text();
            }
            else if(nodeName == "description") {
                QDomNode desNode = node.childNodes().at(0);
                if(desNode.isCDATASection()) {
                    item->mDescription = desNode.toCDATASection().data();
                } else {
                    item->mDescription = node.toElement().text();
                }
            }
            else {
                //Unsupported tag.
            }
        }
        result->items.append(item);
    }
    emit xmlFetched(result);
    return true;
}
